package com.kestrel.space.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.kestrel.space.common.utils.Generator;
import com.kestrel.space.common.utils.LargePage;
import com.kestrel.space.core.mapper.OrganizationMapper;
import com.kestrel.space.core.model.Organization;
import com.kestrel.space.core.query.OrganizationQuery;
import com.kestrel.space.core.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;

/**
 * @author yebolin
 * @date 2024/8/23
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {
    @Autowired
    private OrganizationMapper organizationMapper;

    @Override
    public List<Organization> listContent(OrganizationQuery query, LargePage page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
        }
        Organization organization = BeanUtil.copyProperties(query, Organization.class);
        return organizationMapper.select(organization);
    }

    @Override
    public String saveOrUpdate(Organization organization) {
        String message = "插入成功";
        if (organization.getId() == null) {
            organization.setId(Generator.generateId());
            organizationMapper.insert(organization);
        } else {
            message = "更新成功";
            organizationMapper.updateByPrimaryKeySelective(organization);
        }
        return message;
    }

    @Override
    public String batchSaveOrUpdate(List<Organization> organizationList) {
        String message = "批量插入成功";
        if (CollectionUtils.isEmpty(organizationList)) {
            return "集合为空";
        }
        if(organizationList.get(0).getId() == null){
            for (Organization organization : organizationList) {
                organization.setId(Generator.generateId());
                organizationMapper.insert(organization);
            }
        } else {
            message = "批量更新成功";
            for (Organization organization : organizationList) {
                organization.setId(Generator.generateId());
                organizationMapper.updateByPrimaryKey(organization);
            }
        }
        return message;
    }

}
